package com.example.pceb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pceb.result.Result;
import com.example.pceb.entity.SystemLog;
import com.example.pceb.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/system-logs")
//@CrossOrigin(origins = "*")
public class SystemLogController {
    
    @Autowired
    private SystemLogService systemLogService;
    
    /**
     * 分页获取系统日志
     */
    @GetMapping("/page")
    public Result<Page<SystemLog>> getLogsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) String logger) {
        
        try {
            Page<SystemLog> page = new Page<>(current, size);
            QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
            
            // 按级别筛选
            if (level != null && !level.isEmpty()) {
                queryWrapper.eq("level", level);
            }
            
            // 按日志来源筛选
            if (logger != null && !logger.isEmpty()) {
                queryWrapper.like("logger", logger);
            }
            
            // 按时间倒序排列
            queryWrapper.orderByDesc("create_time");
            
            Page<SystemLog> result = systemLogService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取最新的日志（用于实时监控）
     */
    @GetMapping("/latest")
    public Result<List<SystemLog>> getLatestLogs(
            @RequestParam(defaultValue = "50") Integer limit) {
        
        try {
            QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + limit);
            
            List<SystemLog> logs = systemLogService.list(queryWrapper);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error("获取最新日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取日志统计信息
     */
    @GetMapping("/stats")
    public Result<Object> getLogStats() {
        try {
            // 统计各级别日志数量 - 每次创建新的QueryWrapper
            long infoCount = systemLogService.count(new QueryWrapper<SystemLog>().eq("level", "INFO"));
            long warnCount = systemLogService.count(new QueryWrapper<SystemLog>().eq("level", "WARN"));
            long errorCount = systemLogService.count(new QueryWrapper<SystemLog>().eq("level", "ERROR"));
            long debugCount = systemLogService.count(new QueryWrapper<SystemLog>().eq("level", "DEBUG"));
            
            // 统计总日志数
            long totalCount = systemLogService.count();
            
            return Result.success(new Object() {
                public final long info = infoCount;
                public final long warn = warnCount;
                public final long error = errorCount;
                public final long debug = debugCount;
                public final long total = totalCount;
            });
        } catch (Exception e) {
            return Result.error("获取日志统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 清空日志
     */
    @DeleteMapping("/clear")
    public Result<String> clearLogs() {
        try {
            systemLogService.remove(null);
            return Result.success("日志清空成功");
        } catch (Exception e) {
            return Result.error("清空日志失败: " + e.getMessage());
        }
    }
} 